<?php
class youkutv
{
	public $ShowPageUrl = '';
	public $ShowPageId = '';
	public $TvName = '';
	public $AjaxPageCount = 0;
	public $Path = array();
	public $VShow = array();
	public $Rs = array();
	public $YoukuDomain = 'http://www.youku.com/';
	public $Rewrite = 0;

	public function __construct($ShowPageUrl, $TvName, $Path = '', $Rewrite = 0)
	{
		$this->ShowPageUrl = $ShowPageUrl;
		if(preg_match('/id_([0-9a-zA-Z]+)\.html$/', $ShowPageUrl, $Matches))
		{
			$this->ShowPageId = $Matches[1];
		}
		$TvName = str_replace(':', ' ', $TvName);
		$this->TvName = $TvName;
		$this->Rewrite = $Rewrite;
		$this->Rs['tvname'] = $TvName;
		$this->Rs['copyfrom'] = '|1';//优酷
		$this->Path['root'] = $Path ? $Path : PHPCMS_PATH."uploadfile/";
		$this->makeDir();
	}

	public function makeDir()
	{
		if($this->Path['root'])
		{
			if(!file_exists($this->Path['root']))
			{
				mkdir($this->Path['root'], "0644", true);
			}
			$this->Path['html'] = $this->Path['root']."html/tv/".$this->TvName."/";
			if(!file_exists($this->Path['html']))
			{
				mkdir($this->Path['html'], "0644", true);
			}
			$this->Path['actor'] = $this->Path['root']."image/actor/";
			if(!file_exists($this->Path['actor']))
			{
				mkdir($this->Path['actor'], "0644", true);
			}
			$this->Path['tv'] = $this->Path['root']."image/tv/".$this->TvName."/";
			if(!file_exists($this->Path['tv']))
			{
				mkdir($this->Path['tv'], "0644", true);
			}
		}
	}

	public function getPage($Url, $FileName = "", $Rewrite = 0, $FileSize = 1100)
	{
		$ch = curl_init();
		if(empty($FileName))
		{
			preg_match('/(id_[0-9a-zA-Z]+\.html)$/', $Url, $Matches);
			$FileName = $this->Path['html'].$Matches[1];
		}
		else
		{
			$FileName = $this->Path['html'].$FileName;
		}
		if(!file_exists($FileName) || $Rewrite || (file_exists($FileName) && filesize($FileName) <= $FileSize) )
		{
			$fp = fopen($FileName, "w");

			curl_setopt($ch, CURLOPT_URL, $Url);
			curl_setopt($ch, CURLOPT_FILE, $fp);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_TIMEOUT, 60);
			
			curl_exec($ch);
			curl_close($ch);
			fclose($fp);
		}
		return $FileName;
	}

	public function getShowPage()
	{
		return $this->getPage($this->ShowPageUrl, 'show_page_'.$this->ShowPageId.'.html', 1, 10000);
	}

	public function getAjaxListPage()
	{
		$Page = 1;
		$this->getPage($this->YoukuDomain.'show_eplist/showid_'.$this->ShowPageId.'_type_list_from_ajax_page_'.$Page.'.html', 'ajax_list_'.$Page.'_'.$this->ShowPageId.'.html', 1);
		$Content = file_get_contents($this->Path['html'].'ajax_list_'.$Page.'_'.$this->ShowPageId.'.html');
		
		if(preg_match('/<li class="last" title="最后"><a[^>]*><em class="ico_next"><\/em>([\d]+)<\/a><\/li>/', $Content, $Matches))
		{
			if(isset($Matches[1]) && $Matches[1] > 1)
			{
				while($Page < $Matches[1])
				{
					$Page += 1;
					$this->getPage($this->YoukuDomain.'show_eplist/showid_'.$this->ShowPageId.'_type_list_from_ajax_page_'.$Page.'.html', 'ajax_list_'.$Page.'_'.$this->ShowPageId.'.html', 1);
				}
			}			
		}
		else if(preg_match_all('/<li><a onclick="nova_update[^>]*>(\d+)<\/a><\/li>/', $Content, $Matches))
		{
			if(isset($Matches[1]) && is_array($Matches[1]))
			{
				$Count = $Matches[1][count($Matches[1])-1];
				while($Page < $Count)
				{
					$Page += 1;
					$this->getPage($this->YoukuDomain.'show_eplist/showid_'.$this->ShowPageId.'_type_list_from_ajax_page_'.$Page.'.html', 'ajax_list_'.$Page.'_'.$this->ShowPageId.'.html', 1);
				}
			}	
		}
		$this->AjaxPageCount = $Page;
	}

	public function getActorAvatar($Url, $FileName = "", $Type = "jpg")
	{
		$ch = curl_init();
		
		if(empty($FileName))
		{
			preg_match('/\/([-0-9a-zA-Z]+)$/', $Url, $Matches);
			$FileName = $this->Path['actor'].$Matches[1].".".$Type;
		}
		else
		{
			if(strpos($FileName, '•') !== false)
			{
				$FileName = str_replace('•', '', $FileName);
				$FileName = $this->Path['actor'].iconv("UTF-8", "GBK", $FileName).".".$Type;
				//$FileName = $this->Path['actor'].iconv("UTF-8", "GBK", substr($OldFileName, 0, strpos($OldFileName, '•'))).iconv('UTF-8', 'GBK', '•').iconv("UTF-8", "GBK", substr($OldFileName, strpos($OldFileName, '•')+1)).".".$Type;
			}
			else
			{
				$FileName = $this->Path['actor'].iconv("UTF-8", "GBK", $FileName).".".$Type;
			}
		}
		if(!file_exists($FileName) || (file_exists($FileName) && filesize($FileName) <= 500))
		{
			$fp = fopen($FileName, "w");

			curl_setopt($ch, CURLOPT_URL, $Url);
			curl_setopt($ch, CURLOPT_FILE, $fp);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_TIMEOUT, 60);
			
			curl_exec($ch);
			curl_close($ch);
			fclose($fp);
		}
		return $FileName;
	}

	public function getTvPic($Url, $FileName = "", $IsGBK = true, $Type = "jpg")
	{
		$ch = curl_init();
		if(empty($FileName))
		{
			preg_match('/\/([-0-9a-zA-Z]+)$/', $Url, $Matches);
			$FileName = $this->Path['tv'].$Matches[1].".".$Type;
		}
		else
		{
			if($IsGBK)
			{
				$FileName = $this->Path['tv'].iconv("UTF-8", "GBK", $FileName).".".$Type;
			}
			else
			{
				$FileName = $this->Path['tv'].$FileName.".".$Type;
			}
		}
		if(!file_exists($FileName) || (file_exists($FileName) && filesize($FileName) <= 2500))
		{
			$fp = fopen($FileName, "w");

			curl_setopt($ch, CURLOPT_URL, $Url);
			curl_setopt($ch, CURLOPT_FILE, $fp);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_TIMEOUT, 60);
			
			curl_exec($ch);
			curl_close($ch);
			fclose($fp);
		}
		return $FileName;
	}

	public function parseShowPage()
	{
		$Content = file_get_contents($this->Path['html'].'show_page_'.$this->ShowPageId.'.html');
		$Title = substr($Content, strpos($Content, '<title>') + 7, strpos($Content, '</title>')-strpos($Content, '<title>')-7);
		$this->Rs['title'] = substr($Title, 0, strpos($Title, ' -'));
		$KeyWords = array();
		$KeyWords[] = $this->Rs['title'];
		//$this->Rs['keywords'] = $this->Rs['title'];
		$Year = substr($Content, strpos($Content, '<span class="pub">')+18, 4);
		$this->Rs['year'] = $Year;
		/*
		 $Type = substr($Content, strpos($Content, '<ul class="baseinfo">')+21, strpos($Content, '<span id="infoShort" class="short">')-(strpos($Content, '<ul class="baseinfo">')+21));
		 preg_match_all('/<a target="_blank"[^>]*>([^<]*)<\/a>/', $Type, $Matches);
		 if(isset($Matches[1]) && is_array($Matches[1]))
		 {
			$this->Rs['area'] = $Matches[1][0];
			$TypeStr = implode(',', $Matches[1]);
			$this->Rs['tvtype'] = substr($TypeStr, strpos($TypeStr, ',')+1);
			}
			*/
		preg_match('/<a[\w\W]*?charset="411-3-5-[^>]*>([^<]*)<\/a>/', $Content, $Matches);
		if(isset($Matches[1]))
		{
			$this->Rs['area'] = $Matches[1];
		}
		preg_match_all('/<a[\w\W]*?charset="411-3-6-[^>]*>([^<]*)<\/a>/', $Content, $Matches);
		if(isset($Matches[1]) && is_array($Matches[1]))
		{
			$this->Rs['tvtype'] = implode(',', $Matches[1]);
		}
		preg_match('/<em class="num">([^<]*)<\/em>/', $Content, $Matches);
		if(isset($Matches[1]))
		{
			$this->Rs['rate'] = $Matches[1];
		}
		preg_match('/<a charset="411-1-9"[^>]*><img src="([^"]*)"[\w\W]*?\/><\/a>/', $Content, $Matches);
		if(isset($Matches[1]))
		{
			$this->getTvPic($Matches[1], $this->TvName, false);
			$UploadUrl = pc_base::load_config('system','upload_url');
			//$this->Rs['tvpic'] = WEB_PATH."uploadfile/image/tv/".$this->TvName."/".$this->Rs['title'].".jpg";
			$this->Rs['tvpic'] = $UploadUrl."image/tv/".$this->TvName."/".$this->TvName.".jpg";
			//$this->Rs['tvpic'] = $UploadUrl."image/tv/".$this->TvName."/".iconv("UTF-8", "GBK", $this->Rs['title']).".jpg";
			$this->Rs['thumb'] = $this->Rs['tvpic'];
		}
		if(preg_match('/<a charset="411-1-8"[^>]*><img src="([^"]*)"[^>]*?><\/a>/', $Content, $Matches) && (!isset($this->Rs['tvpic'])||empty($this->Rs['tvpic'])))
		{
			$this->getTvPic($Matches[1], $this->TvName, false);
			$UploadUrl = pc_base::load_config('system','upload_url');
			//$this->Rs['tvpic'] = WEB_PATH."uploadfile/image/tv/".$this->TvName."/".$this->Rs['title'].".jpg";
			$this->Rs['tvpic'] = $UploadUrl."image/tv/".$this->TvName."/".$this->TvName.".jpg";
			$this->Rs['thumb'] = $this->Rs['tvpic'];
			//$this->Rs['thumb'] = $UploadUrl."image/tv/".$this->TvName."/".iconv("UTF-8", "GBK", $this->Rs['title']).".jpg";
		}
		preg_match('/<span[\s]+id="show_info_short"[^>]*?>([\w\W]*?)<\/span>/', $Content, $Matches);
		if(isset($Matches[1]))
		{
			$this->Rs['contentshort'] = $Matches[1];
		}
		else if(preg_match('/<li[\s]+class="statdesc">[\s]*?<span>([\w\W]*?)<\/span>[\s]+<\/li>/', $Content, $Matches))
		{
			$this->Rs['contentshort'] = $Matches[1];
		}
		preg_match('/<span[\s]+id="show_info_long"[^>]*?>([\w\W]*?)<\/span>/', $Content, $Matches);
		if(isset($Matches[1]))
		{
			$this->Rs['contentlong'] = $Matches[1];
			if(!isset($this->Rs['contentshort']) || empty($this->Rs['contentshort']))
			{
				$this->Rs['contentshort'] = mb_substr($this->Rs['contentlong'], 0, 255, 'UTF-8');
			}
		}
		else
		{
			$this->Rs['contentlong'] = $this->Rs['contentshort'];
		}
		$this->Rs['content'] = '<div class="v_story">'.$this->Rs['contentlong'].'</div>';

		if(preg_match('/<h6>演员:<\/h6>\s+<div\s+class="users">([\w\W]*?)<\/div><!--\.users-->/', $Content, $Matches))
		{
			if(preg_match_all('/<img\s+src="([\w\W]*?)"\s+alt="([\w\W]*?)"\s+\/>/', $Matches[1], $Matches2))
			{
				if(isset($Matches2[2]))
				{
					$Actors = str_replace(array('　'), array(''), $Matches2[2]);
					$this->Rs['actor'] = ','.implode(',', $Actors).',';
					$Actor = array_slice($Actors, 0, 4);
					$KeyWords = array_merge($KeyWords, $Actor);

				}

				if(isset($Matches2[1]) && is_array($Matches2[1]))
				{
					foreach($Matches2[1] as $Key => $Val)
					{
						$this->getActorAvatar($Val, $Matches2[2][$Key]);
					}
				}
			}

			if(preg_match_all('/<li class="portray">\s+([\w\W]*?)\s+<\/li>/', $Matches[1], $Matches2))
			{
				if(isset($Matches2[1]))
				{
					$Roles = str_replace(array('　'), array(''), $Matches2[1]);
					$this->Rs['role'] = ','.implode(',', $Roles).',';
					$Role = array_slice($Roles, 0, 4);
					$KeyWords = array_merge($KeyWords, $Role);
				}
			}
		}

		if(preg_match('/<h6>导演:<\/h6>\s+<div\s+class="users">([\w\W]*?)<\/div><!--\.users-->/', $Content, $Matches))
		{
			if(preg_match_all('/<img\s+src="([\w\W]*?)"\s+alt="([\w\W]*?)"\s+\/>/', $Matches[1], $Matches2))
			{
				if(isset($Matches2[2]))
				{
					$Directors = str_replace(array('　'), array(''), $Matches2[2]);
					$this->Rs['director'] = implode(',', $Directors);
					$KeyWords = array_merge($KeyWords, $Directors);

				}

				if(isset($Matches2[1]) && is_array($Matches2[1]))
				{
					foreach($Matches2[1] as $Key => $Val)
					{
						$this->getActorAvatar($Val, $Matches2[2][$Key]);
					}
				}
			}
		}

		if(preg_match('/<h6>编剧:<\/h6>\s+<div\s+class="users">([\w\W]*?)<\/div><!--\.users-->/', $Content, $Matches))
		{
			if(preg_match_all('/<img\s+src="([\w\W]*?)"\s+alt="([\w\W]*?)"\s+\/>/', $Matches[1], $Matches2))
			{
				if(isset($Matches2[2]))
				{
					$Playwrights = str_replace(array('　'), array(''), $Matches2[2]);
					$this->Rs['playwright'] = implode(',', $Playwrights);
					$KeyWords = array_merge($KeyWords, $Playwrights);
				}

				if(isset($Matches2[1]) && is_array($Matches2[1]))
				{
					foreach($Matches2[1] as $Key => $Val)
					{
						$this->getActorAvatar($Val, $Matches2[2][$Key]);
					}
				}
			}
		}

		if(preg_match('/<h6>监制:<\/h6>\s+<div\s+class="users">([\w\W]*?)<\/div><!--\.users-->/', $Content, $Matches))
		{
			if(preg_match_all('/<img\s+src="([\w\W]*?)"\s+alt="([\w\W]*?)"\s+\/>/', $Matches[1], $Matches2))
			{
				if(isset($Matches2[2]))
				{
					$Managers = str_replace(array('　'), array(''), $Matches2[2]);
					$this->Rs['manager'] = implode(',', $Managers);
					$KeyWords = array_merge($KeyWords, $Managers);
				}

				if(isset($Matches2[1]) && is_array($Matches2[1]))
				{
					foreach($Matches2[1] as $Key => $Val)
					{
						$this->getActorAvatar($Val, $Matches2[2][$Key]);
					}
				}
			}
		}


		/*
		preg_match_all('/<li class="name"><a charset="[^>]*>([\w\W]*?)<\/a><\/li>/', $Content, $Matches);
		if(isset($Matches[1]))
		{
			$Actors = str_replace(array('　'), array(''), $Matches[1]);
			$this->Rs['actor'] = ','.implode(',', $Actors).',';
			$Actor = array_slice($Actors, 0, 4);
			$KeyWords = array_merge($KeyWords, $Actor);
		}
		preg_match_all('/<li class="role" title="([\w\W]*?)">[\w\W]*?<\/li>/', $Content, $Matches);
		if(isset($Matches[1]))
		{
			$Roles = str_replace(array('　'), array(''), $Matches[1]);
			$this->Rs['role'] = ','.implode(',', $Roles).',';
			$Role = array_slice($Roles, 0, 4);
			$KeyWords = array_merge($KeyWords, $Role);
		}
		preg_match_all('/<li class="photo"><a[^>]*><img src="([^"]*?)" alt="([\w\W]*?)"><\/a><\/li>/', $Content, $Matches);
		if(isset($Matches[1]) && is_array($Matches[1]))
		{
			foreach($Matches[1] as $Key => $Val)
			{
				$this->getActorAvatar($Val, $Matches[2][$Key]);
			}
		}
		preg_match_all('/<a charset="411-13-1-[\d]+" [^>]*>([\w\W]*?)<\/a>/', $Content, $Matches);
		if(isset($Matches[1]) && is_array($Matches[1]))
		{
			$Directors = str_replace(array('　'), array(''), $Matches[1]);
			$this->Rs['director'] = implode(',', $Directors);
			$KeyWords = array_merge($KeyWords, $Directors);
		}
		preg_match_all('/<a charset="411-13-4-[\d]+" [^>]*>([\w\W]*?)<\/a>/', $Content, $Matches);
		if(isset($Matches[1]) && is_array($Matches[1]))
		{
			$Playwrights = str_replace(array('　'), array(''), $Matches[1]);
			$this->Rs['playwright'] = implode(',', $Playwrights);
			$KeyWords = array_merge($KeyWords, $Playwrights);
		}
		preg_match_all('/<a charset="411-13-5-[\d]+" [^>]*>([\w\W]*?)<\/a>/', $Content, $Matches);
		if(isset($Matches[1]) && is_array($Matches[1]))
		{
			$Managers = str_replace(array('　'), array(''), $Matches[1]);
			$this->Rs['manager'] = implode(',', $Managers);
		}
		*/
		
		$KeyWords = array_unique($KeyWords);
		$KeyWords = str_replace(array(' ', '　'), array('', ''), $KeyWords);
		$this->Rs['keywords'] = implode(' ', $KeyWords);
		
		unset($Content);
	}

	public function parseAjaxListPage()
	{
		if($this->AjaxPageCount > 0)
		{
			$Page = 1;
			while($Page <= $this->AjaxPageCount)
			{
				$Content = file_get_contents($this->Path['html'].'ajax_list_'.$Page.'_'.$this->ShowPageId.'.html');
				preg_match_all('/<li class="v_thumb"><img src="([^"]*)" alt="([^"]*)"[\w\W]*?\/><\/li>/', $Content, $Matches);
				if(isset($Matches[1]) && is_array($Matches[1]))
				{
					foreach($Matches[1] as $Key => $Val)
					{
						$this->Rs['subtitle'] .= $Matches[2][$Key].',';
						$this->getTvPic($Val, $Matches[2][$Key]);
					}
				}
				preg_match_all('/<li class="v_link"><a charset="41[12]-4-3-[\d]+"[\w\W]*?href="([^"]*)"[\w\W]*?><\/a><\/li>/', $Content, $Matches);
				if(isset($Matches[1]) && is_array($Matches[1]))
				{
					foreach($Matches[1] as $Key => $Val)
					{
						$Id = substr($Val, strpos($Val, 'id_')+3, strpos($Val, '.html')-strpos($Val, 'id_')-3);
						$this->VShow[] = $Id;
						$this->getPage($Val, 'v_show_'.$Id.'.html', 0, 5000);
					}
				}
				preg_match_all('/<div class="v_desc">([\w\W]*?)<\/div>/', $Content, $Matches1);
				preg_match_all('/<div class="v_desc" style="display:none;">([\w\W]*?)<\/div>/', $Content, $Matches2);
				if(isset($Matches1[1]) && is_array($Matches1[1]))
				{
					if(isset($Matches2[1]) && is_array($Matches2[1]) && count($Matches2[1]) == count($Matches1[1]))
					{
						foreach($Matches1[1] as $Key => $Val)
						{
							$this->Rs['subcontentshort'] .= $Val.'|||';
							$this->Rs['subcontentlong'] .= $Matches2[1][$Key].'|||';
							$this->Rs['content'] .= '<p>[page]</p><div class="v_story">'.$Matches2[1][$Key].'</div>';
						}
					}
					else
					{
						foreach($Matches1[1] as $Key => $Val)
						{
							$this->Rs['subcontentshort'] .= $Val.'|||';
							$Find = 0;
							foreach($Matches2[1] as $K=> $V)
							{
								if(strstr($V, substr($Val, 0, strpos($Val, '...'))) !== false)
								{
									$Find = 1;
									$this->Rs['subcontentlong'] .= $V.'|||';
									$this->Rs['content'] .= '<p>[page]</p><div class="v_story">'.$V.'</div>';
									unset($Matches2[1][$K]);
									break;
								}
							}
							if($Find == 0)
							{
								$this->Rs['subcontentlong'] .= $Val.'|||';
								$this->Rs['content'] .= '<p>[page]</p><div class="v_story">'.$Val.'</div>';
							}
						}
					}
				}
				$Page += 1;
				unset($Content);
			}
			$this->Rs['subtitle'] = $this->Rs['subtitle'] ? substr($this->Rs['subtitle'], 0, -1) : '';
			$this->Rs['subcontentshort'] = $this->Rs['subcontentshort'] ? substr($this->Rs['subcontentshort'], 0, -3) : '';
			$this->Rs['subcontentlong'] = $this->Rs['subcontentlong'] ? substr($this->Rs['subcontentlong'], 0, -3) : '';
		}
	}

	public function parseVShowPage()
	{
		if(is_array($this->VShow) && $this->VShow)
		{
			foreach($this->VShow as $Key => $Val)
			{
				$Content = file_get_contents($this->Path['html'].'v_show_'.$Val.'.html');
				preg_match('/<input type="text"\s+class="[^"]*"\s+id="link2"\s+value="([^"]*)"\s?>/', $Content, $Matches);
				if(isset($Matches[1]) && $Matches[1])
				{
					$this->Rs['flash'] .= $Matches[1].',';
				}
			}
			$this->Rs['flash'] = $this->Rs['flash'] ? substr($this->Rs['flash'], 0, -1) : '';
		}
	}

	public function getAndParse()
	{
		$this->getShowPage();
		$this->parseShowPage();
		$this->getAjaxListPage();
		$this->parseAjaxListPage();
		$this->parseVShowPage();
		
		return $this->Rs;
	}
}


?>